var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var queryurl = config.BASEPATH+'batch/report/pageSellDetailReport';
var querysizeurl = config.BASEPATH+'batch/report/pageSellDetailSizeReport';
var querysizetitleurl = config.BASEPATH+'batch/report/sell_detail_size_title';
var _height = $(parent).height()-180,_width = $(parent).width()-32;
var api = frameElement.api;
if(api == undefined){
	$("#btn_close").hide();
	_height = $(parent).height()-285;
	_width = $(parent).width()-192;
}
var needListRefresh = false;//列表模式
var needSizeRefresh = false;//尺码模式
var showMode = {
	display:function(mode){
		$("#CurrentMode").val(mode);
		$("a[name='mode-btn']").removeClass("on");
		$("#list-grid").hide();
		$("#size-grid").hide();
		if(mode == 0){
			$("#listBtn").addClass("on");
			$("#list-grid").show();
			showMode.refreshList();
		}else if(mode == 1){
			$("#sizeBtn").addClass("on");
			$("#size-grid").show();
			showMode.refreshSize();
		}
	},
	refreshList:function(){//列表模式刷新数据
		if(!needListRefresh){
    		return;
    	}
    	THISPAGE.reloadData();
    	needListRefresh = false;
	},
	refreshSize:function(){
		if(!needSizeRefresh){
			return;
		}
		$.ajax({
			type:"POST",
			url:querysizetitleurl+'?'+THISPAGE.buildParams(),
			cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
                    var titles = data.data.titles;
                    var sizeCodeMap = data.data.sizeCodeMap;
                    $('#sizeGrid').GridUnload();
                    THISPAGE.initSizeGroupGrid(titles, sizeCodeMap);
                    needSizeRefresh = false;
				}else{
					Public.tips({type: 1, content : data.message});
				}
            }
        });
	},
	refresh:function(){
		var currentMode = $("#CurrentMode").val();
    	if(currentMode == '0'){//列表模式
    		needListRefresh = true;
    		showMode.refreshList();
        	needSizeRefresh = true;
    	}else if(currentMode == '1'){//尺码模式
    		needSizeRefresh = true;
    		showMode.refreshSize();
    		needListRefresh = true;
    	}
	}
};

var handle = {
	formatProfit:function(val, opt, row){
		return PriceLimit.formatMoney(row.sel_unitmoney-row.sel_costmoney);
	},
	formatProfitSize:function(val, opt, row){
		return PriceLimit.formatMoney(row.unit_money-row.cost_money);
	},
	formatType:function(val, opt, row){
		if(val == 0){
			return '批发单';
		}else if(val == 1){
			return '退货单';
		}
		return val;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_se_type = $("#td_se_type").cssRadio({ callback: function($_obj){
			$("#se_type").val($_obj.find("input").val());
		}});
		this.initParams();
		Public.buildSeasonCombo("span_pd_season", "pd_season");
		Public.buildYearCombo("span_pd_year", "pd_year");
		needListRefresh = false;//列表模式
        needSizeRefresh = true;//尺码模式
	},
	initParams:function(){
		if(api == undefined){
			return;
		}
		var params = api.data;
		$("#begindate").val($.trim(params.begindate));
		$("#enddate").val($.trim(params.enddate));
		$("#client_name").val($.trim(params.client_name));
		$("#se_client_code").val($.trim(params.se_client_code));
		$("#depot_name").val($.trim(params.depot_name));
		$("#se_depot_code").val($.trim(params.se_depot_code));
		$("#se_manager").val($.trim(params.se_manager));
		$("#bd_name").val($.trim(params.bd_name));
		$("#bd_code").val($.trim(params.bd_code));
		$("#tp_name").val($.trim(params.tp_name));
		$("#tp_code").val($.trim(params.tp_code));
		$("#pd_season").val($.trim(params.pd_season));
		$("#pd_year").val($.trim(params.pd_year));
		$("#pd_code").val($.trim(params.pd_code));
		$("#pd_name").val($.trim(params.pd_name));
		if($.trim(params.se_type) != ''){
			THISPAGE.$_se_type.setValue(parseInt(params.se_type)+1);
		}
	},
	initGrid:function(){
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter,align:'center'},
	    	{label:'日期',name: 'se_make_date',index:'se_make_date',width:100},
	    	{label:'单据编号',name: 'sel_number',index:'sel_number',width:135},
	    	{label:'单据类型',name: 'sel_type',index:'sel_type',width:100,formatter: handle.formatType,align:'center'},
	    	{label:'客户名称',name: 'client_name',index:'client_name',width:100},
	    	{label:'仓库名称',name: 'depot_name',index:'depot_name',width:100},
	    	{label:'商品货号',name: 'pd_no',index:'pd_no',width:100},
	    	{label:'',name: 'sel_pd_code',index:'sel_pd_code',width:100,hidden:true},
	    	{label:'商品名称',name: 'pd_name',index:'pd_name',width:100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60,align:'center'},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60,align:'center'},
	    	{label:'数量',name: 'sel_amount', index: 'sel_amount', width: 70,align:'right'},
	    	{label:'单价',name: 'sel_unitprice', index: 'sel_unitprice', width: 80,align:'right',formatter: PriceLimit.formatByBatch},
	    	{label:'金额',name: 'sel_unitmoney', index: 'sel_unitmoney', width: 80,align:'right',formatter: PriceLimit.formatByBatch},
	    	{label:'零售价',name: 'sel_retailprice', index: 'sel_retailprice', width: 80,align:'right',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'sel_retailmoney', index: 'sel_retailmoney', width: 80,align:'right',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'sel_costprice', index: 'sel_costprice', width: 80,align:'right',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'sel_costmoney', index: 'sel_costmoney', width: 80,align:'right',formatter: PriceLimit.formatByCost},
	    	{label:'利润',name: 'profit',index:'profit',width:100, align:'right',formatter: handle.formatProfit},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'季节',name: 'pd_season', index: 'pd_season', width: 80,align:'center'},
	    	{label:'年份',name: 'pd_year', index: 'pd_year', width: 80,align:'center'}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'local',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:false,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'sel_id'  //图标ID
			},
			loadComplete: function(data){
				var footer = $('#grid').footerData()
				footer.se_make_date = "合计";
				footer.profit = "";
				delete footer.operate;
		    	$('#grid').footerData('set',footer);
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initSizeGroupGrid:function(dyColNames, sizeCodeMap) {
		var self=this;
        var headers = [];
        var dyns = dyColNames;
        var dySize = dyns.length;
        var dms = [];
        for (var i = 0; i < dyns.length; i++) {
            var dys = dyns[i];
            for (var j = 0; j < dys.length; j++) {
                var dyss = null;
                dyss = dys[j].split('_AND_');
                if (i == 0 && j == 0) {
                    dyns[i][j] = dyss[0];
                }
                headers.push(dyss[1]);
                dms.push({label:dyss[1],name: 'amountMap.'+dyss[0], index: dyss[0], width: 45, title: false, align: 'right', sorttype: 'int', sortable: false});
            }
            break;
        }
		var colModel = [
            {label:'',name: 'sel_szg_code', hidden: true},
            {label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter,align:'center'},
            {label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
            {label:'',name: 'sel_pd_code', index: 'sel_pd_code', width: 100, hidden: true},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'sel_cr_code', width: 80},
	    	{label:'杯型',name: 'br_name', index: 'sel_br_code', width: 80},
        ];
        colModel = colModel.concat(dms);
        colModel = colModel.concat([
            {label:'数量',name: 'totalamount',	index:'totalamount',	width: 70, align: 'right', sorttype: 'int', sortable: false},
            {label:'批发价',name: 'sel_unitprice', index: 'sel_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
            {label:'零售价',name: 'sel_retailprice', index: 'sel_retailprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'批发金额',name: 'unit_money', index: 'unit_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByBatch},
	    	{label:'零售金额',name: 'sell_money', index: 'sell_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'cost_money', index: 'cost_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'利润',name: 'profit',index:'profit',width:100, align:'right',formatter: handle.formatProfitSize},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'季节',name: 'pd_season', index: 'pd_season', width: 80,align:'center'},
	    	{label:'年份',name: 'pd_year', index: 'pd_year', width: 80,align:'center'}
	    ]);
        $('#sizeGrid').jqGrid({
			url: querysizeurl+'?'+THISPAGE.buildParams(),
            datatype: 'json',
            autowidth: true,
			height: _height,
            gridview: true,
            colModel: colModel,
            rownumbers: true,//行号
            pager: '#sizePage',//分页
            pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条', 
            viewrecords: true,
            rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
            shrinkToFit: false,//表格是否自动填充
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'sel_id'  //图标ID
			},
			loadComplete: function(data) {
				var footData = {};
				if (dms != null && dms.length > 0) {
					for ( var i = 0; i < dms.length; i++) {
						footData[dms[i].name] = $('#sizeGrid').getCol(dms[i].name,false,'sum');
					}	
				}
				footData["totalamount"] = $('#sizeGrid').getCol("totalamount",false,'sum');
				footData["unit_money"] = $('#sizeGrid').getCol("unit_money",false,'sum');
				footData["sell_money"] = $('#sizeGrid').getCol("sell_money",false,'sum');
				footData["cost_money"] = $('#sizeGrid').getCol("cost_money",false,'sum');
				footData["profit"] = '';
				footData["pd_no"] = '合计';
				$("#sizeGrid").footerData('set',footData);
			},
			gridComplete:function(){
				Public.resizeSpecifyGrid('sizeGrid', 110 + (dyns.length * 32),32);
			},
			loadError: function(xhr, status, error) {
                Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
            onSelectRow: function (rowId, status) {
                var sizeG = $("#sizeGrid").jqGrid("getRowData", rowId).sel_szg_code;
                var bg = $('[sizeGCode=' + sizeG + ']').css("background");
                if (bg == 'none') {
                    return;
                }
                $("[sizeGCode]").css("background-color", '#eee');
                $('[sizeGCode=' + sizeG + ']').css({ "background": "none", "background-color": "#F8FF94"});
            }
	    });
        if (dySize >= 2) {
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders:[]
            });
            $('#sizeGrid').jqGrid("setComplexGroupHeaders", {
                complexGroupHeaders: {startColumnName: 'amountMap.'+dyns[0][0], numberOfColumns: dyns[0].length},
                rowspan: dySize,
                topTitle:true
            });
            for (var key in sizeCodeMap) {
                $('#sizeGrid').jqGrid("setComplexGroupHeaders",{
                    complexGroupHeaders: {startColumnName: 'amountMap.'+dyns[0][0], numberOfColumns: dyns[0].length},
                    rowspan: dySize,
                    sizeGroupCode: key,
                    titleTextGroup:sizeCodeMap[key],
                    topTitle:false
                });
            }
        }else{
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders: [{startColumnName: 'amountMap.'+dyns[0][0], numberOfColumns: dyns[0].length, titleText: '尺码'}]
            });
        }
    },
	buildParams : function(){
		var params = '';
		params += 'se_type='+$("#se_type").val();
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&se_client_code='+$("#se_client_code").val();
		params += '&se_depot_code='+$("#se_depot_code").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&se_manager='+Public.encodeURI($("#se_manager").val());
		params += '&pd_code='+$("#pd_code").val();
		return params;
	},
	reset:function(){
		$("#pd_code").val("");
		$("#pd_name").val("");
		$("#se_manager").val("");
		$("#client_name").val("");
		$("#se_client_code").val("");
		$("#depot_name").val("");
		$("#se_depot_code").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_se_type.setValue(0);
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			showMode.refresh();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			Public.hideConstion();
			showMode.refresh();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).sel_pd_code);
        });
		$('#sizeGrid').on('click', '.operating .ui-icon-image', function (e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			viewProductImg($("#grid").jqGrid("getRowData", id).sel_pd_code);
		});
	}
}
THISPAGE.init();